import { Injectable } from '@nestjs/common';
import { CreateDictDto } from './dto/create-dict.dto';
import { UpdateDictDto } from './dto/update-dict.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Dict } from './entities/dict.entity';
import { DataSource, Repository } from 'typeorm';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { DictSon } from '../dict-son/entities/dict-son.entity';

@Injectable()
export class DictService {
  constructor(
    @InjectRepository(Dict)
    private dictRepository: Repository<Dict>,
    private dataSource: DataSource,
  ) {}

  create(createDictDto: CreateDictDto) {
    return this.dictRepository.save(createDictDto);
  }

  findAll(pageQuery: PageQuery<Dict>) {
    return this.dictRepository.findAndCount(buildQuery(pageQuery));
  }

  findOne(id: number) {
    return this.dictRepository.findOneBy({ id });
  }

  update(id: number, updateDictDto: UpdateDictDto) {
    return this.dictRepository.update({ id }, updateDictDto);
  }

  async remove(id: number) {
    await this.dictRepository.findOneByOrFail({ id });
    await this.dataSource.transaction(async (tr) => {
      await tr.softDelete(DictSon, { dict: { id } });
      await tr.softDelete(Dict, { id });
    });
    return true;
  }

  /**
   * 通过code找到孩子(有缓存)
   * @param code
   */
  async findDictSonByCode(code: string) {
    const dict = await this.dictRepository.findOne({
      where: { code },
      relations: {
        dictSons: true,
      },
      // 这个字典经常访问,就缓存10秒钟好了
      cache: 10 * 1000,
    });
    if (dict) {
      return dict.dictSons;
    } else {
      throw new Error('请先创建一个 ' + code + ' 字典');
    }
  }
}
